import { Prefab } from 'cc';
import { _decorator, Component, Node } from 'cc';
import Design from '../bundle/utils/Design';
import { instantiate } from 'cc';
import { Brick } from '../bundle/game/src/scripts/Brick';
import { EventTouch } from 'cc';
import { input } from 'cc';
import { Input } from 'cc';
import { Vec2 } from 'cc';
import { PhysicsSystem } from 'cc';
import { Camera } from 'cc';
import { EditorManager } from './EditorManager';
import { PointInfo } from '../bundle/utils/Types';
import { Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EditorOperate')
export class EditorOperate extends Component {
    @property( {type: Node, displayName: "地板定位" } )
    floorNode: Node = null;
    
    @property( {type: Prefab, displayName: "地砖预制体" } )
    tilePre: Prefab = null;
    
    @property( {type: Prefab, displayName: "六边形块预制体" } )
    brickPre: Prefab = null;
    
    @property({ type: Camera, displayName: "摄像头" })
    camera: Camera;
    
    @property({ type: EditorManager, displayName: "编辑管理器" })
    manager: EditorManager;
    
    private startTouchPos: Vec2 = new Vec2(); // 触摸开始位置
    private isTouching: boolean = false; // 是否正在触摸
    private rotationSpeed: number = 0.25; // 旋转速度，值越大旋转越快

    protected onLoad(): void {
        this.manager = this.getComponent(EditorManager)
    }

    start() {
        input.on (Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on (Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on (Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    protected onDestroy(): void {
        input.off(Input.EventType.TOUCH_START)
        input.off(Input.EventType.TOUCH_MOVE)
        input.off(Input.EventType.TOUCH_END)
    }    

    // ---------------------- 事件 ---------------------- //
    private onTouchStart(event: EventTouch) {
        // 记录触摸开始位置
        event.getStartLocation(this.startTouchPos);
        this.isTouching = true;
    }

    private onTouchMove(event: EventTouch) {
        if (!this.isTouching) return;
        
        // 获取当前触摸位置
        const touchPos = event.getLocation(new Vec2());
        const deltaX = touchPos.x - this.startTouchPos.x; // 计算滑动的水平距离

        // 根据滑动距离计算旋转角度
        const rotationY = deltaX * this.rotationSpeed;

        // 更新目标节点的旋转
        const currentRotation = this.floorNode.eulerAngles;
        this.floorNode.setRotationFromEuler(new Vec3(currentRotation.x, currentRotation.y + rotationY, currentRotation.z));

        // 更新开始位置
        this.startTouchPos.set(touchPos);
    }

    // 触摸屏幕，目标为选中的 3D 对象
    private onTouchEnd(e: EventTouch): void {
        const brickCom = this.getCurrentBrick(e.getLocation())
        if (brickCom) {
            this.manager.operateAtLoc(brickCom.x, brickCom.z, this.floorNode.getChildByName(brickCom.x + "_" + brickCom.z))
        }
    }

    // ---------------------- 内部调用 ---------------------- //
    // 射线检查，来获取块
    private rayCheck(pos: Vec2) {
        let ray = this.camera.screenPointToRay(pos.x, pos.y)        
        // 如果选中了节点
        if (PhysicsSystem.instance.raycastClosest(ray) == true) {
            // 获取射线最短的检测结果
            var checkNode = PhysicsSystem.instance.raycastClosestResult.collider.node
            return checkNode
        }

        return null
    }

    // 获取当前位置的六边形块
    private getCurrentBrick(loc: Vec2): Brick {
        const result = this.rayCheck(loc)
        if (result != null) {
            var brickCom = result.getComponent(Brick)
            if (brickCom) {
                return brickCom
            }
        }

        return null
    }

    // ---------------------- 外部调用 ---------------------- //
    public drawFloor(horizontalSize: number, verticalSize: number) {
        this.floorNode.removeAllChildren()

        for (var ix = 0; ix < horizontalSize; ix++) {
            for (var iz = 0; iz < verticalSize; iz++) {
                
                const posX = ix * Design.panelWidth - 0.5 * (horizontalSize - 1) * Design.panelWidth +  ((iz % 2 != 0) ? Design.panelWidth / 2 : 0 )
                const posZ = iz * Design.panelHeight - 0.5 * (verticalSize - 1) * Design.panelHeight

                const tileNode = instantiate( this.tilePre )
                tileNode.setPosition(posX, 0, posZ)
                tileNode.parent = this.floorNode
                tileNode.name = ix + "_" + iz
                tileNode.getComponent(Brick).x = ix
                tileNode.getComponent(Brick).z = iz
            }
        }
    }

    // 添加积木块
    public updateBrick(x: number, z: number, info: PointInfo) {
        const towerNode = this.floorNode.getChildByName(x + "_" + z)
        towerNode.getChildByName("柱体").removeAllChildren()

        for (var i = 0; i < info.blocks.length; i++) {
            const brickNode = instantiate(this.brickPre)
            brickNode.parent = towerNode.getChildByName("柱体")
            brickNode.setPosition(0, (i + 1) * Design.brickConfig.brickSpace , 0)
            brickNode.getComponent(Brick).color = info.blocks[i]
            brickNode.getComponent(Brick).setLoc(x, z)
            brickNode.name = "六边形_" + info.blocks[i]
        }
    }
}


